package org.example.impl;

import org.example.DAO.CommentDao;
import org.example.entity.Comment;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CommentDaoImpl implements CommentDao {
    private final DataSource dataSource;

    public CommentDaoImpl(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public boolean saveComment(Comment comment) throws SQLException {
        String sql = "INSERT INTO comments (user_id, username, content_id, content_type, " +
                "rating, content, create_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?) " +
                "ON DUPLICATE KEY UPDATE " +
                "rating = VALUES(rating), content = VALUES(content), " +
                "create_time = VALUES(create_time)";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setInt(1, comment.getUserId());
            stmt.setString(2, comment.getUsername());
            stmt.setInt(3, comment.getContentId());
            stmt.setString(4, comment.getContentType());
            stmt.setInt(5, comment.getRating());
            stmt.setString(6, comment.getContent());
            stmt.setTimestamp(7, comment.getCreateTime());

            int affectedRows = stmt.executeUpdate();

            if (affectedRows > 0 && comment.getId() == 0) {
                try (ResultSet rs = stmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        comment.setId(rs.getInt(1));
                    }
                }
            }

            return affectedRows > 0;
        }
    }
    @Override
    public Comment getCommentById(int commentId) throws SQLException {
        String sql = "SELECT c.*, ct.title AS content_title, ct.image_url AS content_image_url, ct.type AS content_type " +
                "FROM comments c " +
                "JOIN contents ct ON c.content_id = ct.id AND c.content_type = ct.type " +
                "WHERE c.id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, commentId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    Comment comment = new Comment();
                    comment.setId(rs.getInt("id"));
                    comment.setUserId(rs.getInt("user_id"));
                    comment.setContentId(rs.getInt("content_id"));
                    comment.setContentType(rs.getString("content_type"));
                    comment.setRating(rs.getInt("rating"));
                    comment.setContent(rs.getString("content"));
                    comment.setCreateTime(rs.getTimestamp("create_time"));


                    return comment;
                }
            }
        }
        return null;
    }
    @Override
    public Comment getUserComment(int userId, int contentId, String contentType) throws SQLException {
        String sql = "SELECT * FROM comments WHERE user_id = ? AND content_id = ? AND content_type = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, userId);
            stmt.setInt(2, contentId);
            stmt.setString(3, contentType);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    Comment comment = new Comment();
                    comment.setId(rs.getInt("id"));
                    comment.setUserId(rs.getInt("user_id"));
                    comment.setContentId(rs.getInt("content_id"));
                    comment.setContentType(rs.getString("content_type"));
                    comment.setRating(rs.getInt("rating"));
                    comment.setContent(rs.getString("content"));
                    comment.setCreateTime(rs.getTimestamp("create_time"));
                    return comment;
                }
            }
        }
        return null;
    }

    @Override
    public boolean addComment(Comment comment) throws SQLException {
        String sql = "INSERT INTO comments (user_id, username, content_id, content_type, rating, content, create_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setInt(1, comment.getUserId());
            stmt.setString(2, comment.getUsername());
            stmt.setInt(3, comment.getContentId());
            stmt.setString(4, comment.getContentType());
            stmt.setInt(5, comment.getRating());
            stmt.setString(6, comment.getContent());
            stmt.setTimestamp(7, comment.getCreateTime());

            int affectedRows = stmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = stmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        comment.setId(rs.getInt(1));
                    }
                }
                return true;
            }
            return false;
        }
    }
    @Override
    public boolean updateComment(Comment comment) throws SQLException {
        String sql = "UPDATE comments SET rating = ?, content = ?, create_time = ? WHERE id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, comment.getRating());
            stmt.setString(2, comment.getContent());
            stmt.setTimestamp(3, comment.getCreateTime());
            stmt.setInt(4, comment.getId());

            return stmt.executeUpdate() > 0;
        }
    }
    @Override
    public List<Comment> getCommentsWithContentByUser(int userId) throws SQLException {
        String sql = "SELECT c.*, ct.title AS content_title, ct.image_url AS content_image_url, ct.type AS content_type " +
                "FROM comments c " +
                "JOIN contents ct ON c.content_id = ct.id AND c.content_type = ct.type " +
                "WHERE c.user_id = ? " +
                "ORDER BY c.create_time DESC";

        List<Comment> comments = new ArrayList<>();
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Comment comment = new Comment();
                    comment.setId(rs.getInt("id"));
                    comment.setUserId(rs.getInt("user_id"));
                    comment.setContentId(rs.getInt("content_id"));
                    comment.setContentType(rs.getString("content_type"));
                    comment.setRating(rs.getInt("rating"));
                    comment.setContent(rs.getString("content"));
                    comment.setCreateTime(rs.getTimestamp("create_time"));

                    // 设置关联内容信息
                    comment.setContentTitle(rs.getString("content_title"));
                    comment.setContentImageUrl(rs.getString("content_image_url"));

                    comments.add(comment);
                }
            }
        }
        return comments;
    }

    @Override
    public boolean isCommentOwner(int commentId, int userId) throws SQLException {
        String sql = "SELECT COUNT(*) FROM comments WHERE id = ? AND user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, commentId);
            stmt.setInt(2, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next() && rs.getInt(1) > 0;
            }
        }
    }

    @Override
    public boolean deleteComment(int commentId, int userId) throws SQLException {
        String sql = "DELETE FROM comments WHERE id = ? AND user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, commentId);
            stmt.setInt(2, userId);
            return stmt.executeUpdate() > 0;
        }
    }
    private Comment mapToComment(ResultSet rs) throws SQLException {
        Comment comment = new Comment();
        comment.setId(rs.getInt("id"));
        comment.setUserId(rs.getInt("user_id"));
        comment.setUsername(rs.getString("username"));
        comment.setContentId(rs.getInt("content_id"));
        comment.setContentType(rs.getString("content_type"));
        comment.setRating(rs.getInt("rating"));
        comment.setContent(rs.getString("content"));
        comment.setCreateTime(rs.getTimestamp("create_time"));
        return comment;
    }


}